<?php

namespace app\beautiful\controller\admin\goods;

use app\BaseController;
use app\beautiful\model\goods\GoodsGroupDetailModel;
use app\beautiful\model\goods\GoodsGroupModel;
use app\beautiful\model\goods\GoodsOtherSkuDetailModel;
use app\beautiful\model\goods\GoodsOtherSkuModel;
use app\beautiful\model\LevelBenefitsModel;
use app\beautiful\model\LevelModel;
use app\beautiful\model\mall\FlashSaleGoodsModel;
use app\beautiful\model\mall\GoodsCategoryModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\GoodsSkuModel;
use app\beautiful\model\mall\PinTuanGoodsModel;
use app\beautiful\model\setting\LevelSettingModel;
use app\common\logic\DataLogic;
use app\common\model\account\ShopAccountModel;
use app\common\model\ProduceModel;
use app\common\model\ShopModel;
use app\common\model\SupplierGoodsModel;
use app\common\model\SupplierModel;
use app\stores\model\promotion\ActivityModel;
use think\facade\Db;


class Goods extends BaseController{

    protected $name='商品';
    protected $set_meal_name='套餐';
    /**
     *产品管理根据分类获取商品或套餐列表
     */
    public function index(){
        $category_id = $this->request->param('category_id/d',0);
        $type = $this->request->param('type/d',0);//1菜单2产品+套餐
        $search = $this->request->param('search');
        $depart_id = $this->request->param('depart_id/d',0);
        $where = [
            ['is_delete','=',0],
            ['shop_id','=',$this->request->shopId],
        ];
        if($type==1){
            $where[]=['type','=',1];
        }
        if($type==2){
            $where[]=['type','IN',[2,3]];
        }
        if($search){
            $where[]=['name','like','%'.$search.'%'];
        }

        //查找分类下所有子分类

        $son = GoodsCategoryModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'status'=>1,'pid'=>$category_id])->find();

        if($son){

            $category = GoodsCategoryModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'status'=>1])->select()->toArray();

            $category_ids = $this->get_all_child($category,$category_id);
        }else{
            $category_ids[] =$category_id;
        }

        //获取分类的产品

        $goods_id_arr = [];

        for($i=0;$i<count($category_ids);$i++){

            $goods_ids = GoodsModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->whereRaw("FIND_IN_SET('{$category_ids[$i]}',category_id)")->column('goods_id');

            $goods_id_arr = array_merge($goods_id_arr,$goods_ids);

        }

        $where[]=['goods_id','IN',$goods_id_arr];

        $level_setting = LevelSettingModel::where(['shop_id'=>$this->request->shopId,'is_selected'=>1])->find();
        //分类名
        $goods_category = GoodsCategoryModel::find($category_id);
        $goodsModel = GoodsModel::with(['sku'=>function($query){
            $query->field('sku_id,goods_id,name,original_price,unit_id,gross,discount_detail,crossed_price')
                ->where(['shop_id'=>$this->request->shopId,'is_delete'=>0])
                ->json(['discount_detail'],true);
        },'unit'=>function($query){
            $query->field('other_sku_detail_id,group_detail_name')
                ->where(['shop_id'=>$this->request->shopId,'is_delete'=>0]);
        }])->json(['discount_detail'],true);

        $order = ['sort'=>'desc'];
        $field = "goods_id,name,unit_id,original_price,vip_price,gross,discount_detail,is_have_sku";
        $append = ['add_time_format'];

        $return = DataLogic::getDataList($goodsModel,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        $list = $return['list'];

        foreach ($list as $k=>$v){
            $list[$k]['member_system_type'] = $level_setting->type;
            if($category_id<1){
                $goods_category = GoodsCategoryModel::find($v['category_id']);
            }
            //分类名
            $list[$k]['category_name'] = empty($goods_category)?'':$goods_category['name'];

            //规格
            if($v['sku']){
                $list[$k]['sku'] = $this->goodsSku($v['sku']);
            }else{
                $list[$k]['sku'][] = [
                    'name'=>$v['name'],
                    'original_price'=>$v['original_price'],
                    'discount_detail'=>$v['discount_detail']
                    ] ;
            }

            $other_sku_ids=[];
            if(!empty($v['other_sku_id'])){
                $other_sku_ids = explode(',',$v['other_sku_id']);
            }

            $list[$k]['like'] = GoodsOtherSkuModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'type'=>1])->whereIn('other_sku_id',$other_sku_ids)->field('other_sku_id,group_name')->select();
            $list[$k]['make'] = GoodsOtherSkuModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'type'=>2])->whereIn('other_sku_id',$other_sku_ids)->field('other_sku_id,group_name')->select();

            $flash_sale = FlashSaleGoodsModel::whereTime('start_time','<=',date('Y-m-d'))->whereTime('end_time','>=',date('Y-m-d'))->where(['status'=>1,'goods_id'=>$v['goods_id']])->find();
            $pin_tuan = PinTuanGoodsModel::whereTime('start_time','<=',date('Y-m-d'))->whereTime('end_time','>=',date('Y-m-d'))->where(['status'=>1,'goods_id'=>$v['goods_id']])->find();
            $activity = ActivityModel::where(['goods_id'=>$v['goods_id'],'status'=>1,'is_delete'=>0])->find();
            $list[$k]['is_flash_sale'] = $flash_sale?1:0;
            $list[$k]['is_pin_tuan'] = $pin_tuan?1:0;
            $list[$k]['is_promotion'] = $activity?1:0;


            //最低折扣
            if($v['vip_discount_type']==1){
                $member_price = array_column($v['discount_detail'], 'member_price');

                $min_price = [
                    'min_discount'=>min($member_price),

                    'min_price'=>min($member_price) * $v['original_price']
                ];

            }else if($v['vip_discount_type']==2){

                $bid_price = array_column($v['discount_detail'], 'bid_price');

                $min_price = [
                    'min_discount'=>min($bid_price),

                    'min_price'=>min($bid_price)
                ];
            }else if($v['vip_discount_type']==3){
                $reduce_price = array_column($v['discount_detail'], 'reduce_price');

                $min_price = [
                    'min_discount'=>max($reduce_price),

                    'min_price'=>$v['original_price']-max($reduce_price)
                ];

            }else{
                $min_price = [];
            }

            $list[$k]['min_discount'] = $min_price;
            if($v['type'] == 3){
                $list[$k]['sku'][] = [
                    'name' => $v['name'],
                    'original_price' => $v['original_price'],
                    'discount_detail' => $v['discount_detail'],
                ];
                $list[$k]['original_price'] = $v['total_value'];
                $list[$k]['crossed_price'] = $v['original_price'];
            }

            //出品部门
            $produce = ProduceModel::info(['goods_id'=>$v['goods_id'],'shop_id'=>$this->request->shopId]);

            $list[$k]['is_select'] = (!empty($produce) && $produce['depart_id']!=$depart_id)?0:1;

            $list[$k]['depart_name'] = !empty($produce)?$produce['depart_name']:null;
            $sg = SupplierGoodsModel::supllierInfo(['goods_id'=>$v['goods_id']],'sg.supplier_id,s.name as supplier_name');
            $list[$k]['supplier_name'] = $sg?$sg['supplier_name']:null;
        }

        $return['list'] = $list;
        $return['member_system_type'] = $level_setting->type;
        return $this->success($return);
    }
    //递归获取所有的子分类的ID
    protected function get_all_child($array,$category_id){
        $arr = array();
        foreach($array as $v){
            if($v['pid'] == $category_id){
                $arr[] = $v['category_id'];
                $arr = array_merge($arr,$this->get_all_child($array,$v['category_id']));
            }
        }
        return $arr;
    }

    protected function goodsSku($sku){
        foreach ($sku as &$v){
            $unit = GoodsOtherSkuDetailModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'other_sku_detail_id'=>$v['unit_id']])->find();
            $v['unit_name'] = $unit?$unit->group_detail_name:null;
        }
        return$sku;
    }

    public function show()

    {

        $category = $this->getCategoryTreeData(0);

        $goods_id = $this->request->param('goods_id/d',0);

        if($goods_id==0) return $this->success(['category'=>$category]);

        $goods = GoodsModel::with(['unit'=>function($query){
            $query->field('other_sku_detail_id,group_detail_name')
                ->where(['shop_id'=>$this->request->shopId,'is_delete'=>0]);
        }])->where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId])
            ->json(['discount_detail','goods_details','products_info'],true)
            ->find();

        if(null === $goods) {

            return $this->error($this->name.'不存在');

        }
        //会员折扣
        $discount_detail = $goods->discount_detail;
        if($goods->vip_discount_type>0 && $discount_detail){

            foreach ($discount_detail as $k=>$v){

                $level = LevelModel::find($v['level_id']);
                $discount_detail[$k]['name']=$level->name;
            }

        }
        //$goods->goods_details = $goods->goods_detai;

        $goods->discount_detail = $discount_detail;
        //个人偏好、制作工艺只需要返回，前端自己匹配

        $other_sku_is = $goods['other_sku_id']?explode(',',$goods['other_sku_id']):$goods['other_sku_id'];

        if($other_sku_is)   $ph = GoodsOtherSkuModel::where(['type'=>1])->whereIn('other_sku_id',$other_sku_is)->field('other_sku_id,group_name')->select()->toArray();
        $goods->ph = $other_sku_is?$ph:[];

        if($other_sku_is)   $gy = GoodsOtherSkuModel::where(['type'=>2])->whereIn('other_sku_id',$other_sku_is)->field('other_sku_id,group_name')->select()->toArray();
        $goods->gy = $other_sku_is?$gy:[];

        $goods->show_type = $goods['show_type']?explode(',',$goods['show_type']):$goods['show_type'];
        $goods->send_type = $goods['send_type']?explode(',',$goods['send_type']):$goods['send_type'];
        $goods->category_id = $goods['category_id']?explode(',',$goods['category_id']):$goods['category_id'];

        if($goods->is_have_sku){
            $sku = GoodsSkuModel::with(['unit'=>function($query){
                    $query->field('other_sku_detail_id,group_detail_name')
                        ->where(['shop_id'=>$this->request->shopId,'is_delete'=>0]);
                }])->where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId])
                    ->json(['discount_detail'],true)
                    ->select()->toArray() ?? [];

            foreach ($sku as $key=>$value){
                $sku_discount_detail = $value['discount_detail'];
                if($sku_discount_detail){
                    foreach ($sku_discount_detail as $k=>$v){
                        $level = LevelModel::find($v['level_id']);
                        $sku[$key]['discount_detail'][$k]['name']=$level?$level->name:'';
                    }
                }

            }

        }else{
            $sku[] = [
                'name'=>$goods->sku_name,
                'original_price'=>$goods->original_price,
                'crossed_price'=>$goods->crossed_price,
                'gross'=>$goods->gross,
                'bar_code'=>$goods->bar_code,
                'unit_id'=>$goods->unit_id,
                'unit'=>$goods->unit,
                'weight'=>$goods->weight,
                'quota'=>$goods->quota,
                'discount_detail'=>$goods->discount_detail,
                'start_sales_num'=>$goods->start_sales_num,
                'is_by_sales'=>$goods->is_by_sales,
                'buying_price'=>$goods->buying_price,
                'sku_info'=>$goods->sku_info,
            ];
        }
        $goods->sku = $sku;

        //分区打印
        $produce = ProduceModel::where(['goods_id'=>$goods->goods_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
        $goods->depart_id = $produce?$produce->depart_id:0;
        //供应商
        $sg = SupplierGoodsModel::supllierInfo(['goods_id'=>$goods_id],'sg.supplier_id,s.name as supplier_name');
        $goods->supplier_id = $sg?$sg['supplier_id']:0;
        $goods->supplier_name = $sg?$sg['supplier_name']:null;
        return $this->success(['category'=>$category,'detail'=>$goods]);

    }

    /**
     * 单规格时存goods表，多规格goods和sku表都存，goods默认sku_detail第一个值
     */
    public function save()

    {

        $goods_id = $this->request->param('goods_id/d',0);

        $type = $this->request->param('type/d',0);

        $name = $this->request->param('name');

        $category_id = $this->request->param('category_id/a',[]);

        $sort = $this->request->param('sort/d',0);

        $other_sku_id = $this->request->param('other_sku_id');

        $vip_discount_type = $this->request->param('vip_discount_type/d',0);

        $cover_img = $this->request->param('cover_img');

        $rotation = $this->request->param('rotation/a',[]);

        //$goods_details = $this->request->param('goods_details','','security_json_or_array');

        $goods_details = $this->request->param('goods_details/a',[]);

        $purchase_information = $this->request->param('purchase_information');

        $is_open_yu = $this->request->param('is_open_yu/d',0);

        $yu_price = $this->request->param('yu_price/f',0);

        $yu_time_type = $this->request->param('yu_time_type/d',1);

        $yu_days = $this->request->param('yu_days/d',0);

        $show_type = $this->request->param('show_type');

        $is_tui = $this->request->param('is_tui/d',0);

        $online_sales = $this->request->param('online_sales/d',-1);

        $scan_code = $this->request->param('scan_code/d',-1);

        $support_business_type = $this->request->param('support_business_type');

        $send_type = $this->request->param('send_type',0);

        $status = $this->request->param('status/d',-1);

        $sku_detail = $this->request->param('sku');

        $fictitious_take_count = $this->request->param('fictitious_take_count/d',0);

        $depart_id = $this->request->param('depart_id/d',0);

        $start_sales_num = $this->request->param('start_sales_num/d',1);

        $supplier_id = $this->request->param('supplier_id/d',0);

        $products_info = $this->request->param('products_info');

        //判断传来的参数

        if(empty($name)) return $this->error('请输入名称');

        if($type<1) return $this->error('type值必传');

        if(empty($category_id)) return $this->error('请选择分类');

        if($start_sales_num<1) return $this->error('起售量不能小于1');

        if(!in_array($is_tui,[0,1])) return $this->error('未设置是否推荐');

        if(!in_array($is_open_yu,[0,1])) return $this->error('未设置是否开启预售');

        if(!in_array($vip_discount_type,[0,1,2,3])) return $this->error('未设置会员价类型');

        if($is_open_yu==1){

            if(empty($yu_price) || $yu_price<=0) return $this->error('请输入预售价格，且不能小于0');

            if(empty($yu_days) || $yu_days <= 0) return $this->error('请输入预售支付后几天发货');

        }
        //判断是否选择了套餐分类
        $set_meal_cate = GoodsCategoryModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'name'=>'套餐'])->find();
        if($set_meal_cate && in_array($set_meal_cate->category_id,$category_id)) return $this->error('产品分类不能选套餐');

        if(!$sku_detail) return $this->error('至少一个规格');


        if($sku_detail){

            $quota=0;

            foreach ($sku_detail as $k => $v){

                if(empty($v['name'])) return $this->error('请输入规格第'.($k+1).'行的名称');

                if(empty($v['unit_id'])) return $this->error('请选择规格第'.($k+1).'行的单位');

                if($v['start_sales_num']<1) return $this->error('第'.($k+1).'行的起售量不能小于1');

                //if(empty($v['bar_code'])) return $this->error('请输入规格第'.($k+1).'行的条码');

                if(empty($v['original_price']) || $v['original_price'] <= 0) return $this->error('请输入规格第'.($k+1).'行的原价，且不能小于0');

                if(empty($v['quota']) || $v['quota'] <= 0) return $this->error('请输入规格第'.($k+1).'行的库存，且不能小于0');

                if($vip_discount_type>0 && empty($v['discount_detail']) )return $this->error('请输入规格第'.($k+1).'行的会员价优惠');

                $quota=$quota+$v['quota'];

            }

        }

        if(empty($cover_img)) return $this->error('请上传缩略图');

        if(empty($rotation)) $rotation[] = $cover_img;

        if(empty($rotation) || !is_array($rotation) || count($rotation)>5) return $this->error('请上传轮播图，且数量不能多余5个');

//        if(empty($goods_details)) return $this->error('请填写商品详情');

//        if(empty($purchase_information)) return $this->error('请输入购买须知');

        //保存操作
        $old_depart_id = 0;
        if($goods_id != 0){

            if(null === $goods= GoodsModel::find($goods_id)) return $this->error($this->name.'不存在');

            //之前的商品不能修改
            if($goods->add_time){

            }
            if($goods->is_delete!=0) return $this->error($this->name.'不存在');

            if($goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

            $pre_cover_img=$goods->cover_img; $pre_rotation=$goods->rotation; $pre_goods_details=$goods_details;

            $produce = ProduceModel::where(['goods_id'=>$goods->goods_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();

            $old_depart_id = $produce?$produce->depart_id:0;

        }else{

            $goods = new GoodsModel();

            $scan_code_goods = new GoodsModel();

            $goods->shop_id = $this->request->shopId;

            $scan_code_goods->shop_id = $this->request->shopId;

            $pre_cover_img=null; $pre_rotation=[]; $pre_goods_details=[];

        }

        Db::startTrans();

        try{
            /*扫码点餐第一版先不做
            $scan_code_goods->name = $goods->name = $name;

            $scan_code_goods->type = $goods->type = $type;

            $scan_code_goods->sku_name = $goods->sku_name = $sku_detail[0]['name'];

            $scan_code_goods->unit_id = $goods->unit_id = $sku_detail[0]['unit_id'];

            $scan_code_goods->bar_code = $goods->bar_code = $sku_detail[0]['bar_code'];

            $scan_code_goods->original_price = $goods->original_price = $sku_detail[0]['original_price'];

            $scan_code_goods->gross = $goods->gross = $sku_detail[0]['gross'];

            $scan_code_goods->quota = $goods->quota = $quota;

            $scan_code_goods->weight = $goods->weight = $sku_detail[0]['weight'];

            $scan_code_goods->category_id = $goods->category_id = implode(',',$category_id);

            $scan_code_goods->sort = $goods->sort = $sort;

            $scan_code_goods->is_tui = $goods->is_tui = $is_tui;

            $scan_code_goods->is_open_yu = $goods->is_open_yu = $is_open_yu;

            $scan_code_goods->vip_discount_type = $goods->vip_discount_type = $vip_discount_type;

            if($is_open_yu == 1){

                $scan_code_goods->yu_price = $goods->yu_price = $yu_price;

                $scan_code_goods->yu_days = $goods->yu_days = $yu_days;

                $scan_code_goods->yu_time_type = $goods->yu_time_type = $yu_time_type;

            }

            $scan_code_goods->cover_img = $goods->cover_img = $cover_img;

            $scan_code_goods->rotation = $goods->rotation = $rotation;

            $scan_code_goods->goods_details = $goods->goods_details = $goods_details;

            $scan_code_goods->purchase_information = $goods->purchase_information = $purchase_information;

            $scan_code_goods->other_sku_id = $goods->other_sku_id = $other_sku_id?implode(',',$other_sku_id):$other_sku_id;

            $scan_code_goods->show_type = $goods->show_type = $show_type?implode(',',$show_type):$show_type;

            $scan_code_goods->online_sales = $goods->online_sales = $online_sales;

            $scan_code_goods->scan_code = $goods->scan_code = $scan_code;

            $scan_code_goods->support_business_type = $goods->support_business_type = $support_business_type?implode(',',$support_business_type):$support_business_type;

            $scan_code_goods->send_type = $goods->send_type = $send_type?implode(',',$send_type):$send_type;

            $scan_code_goods->update_time = $goods->update_time = $this->request->time();

            $scan_code_goods->status = $goods->status = $status;

            $scan_code_goods->is_have_sku = $goods->is_have_sku = count($sku_detail)>1?1:0;

            $scan_code_goods->discount_detail = $goods->discount_detail = json_encode($sku_detail[0]['discount_detail'],true);
            */

            $goods->name = $name;

            $goods->type = $type;

            $goods->sku_name = $sku_detail[0]['name'];

            $goods->unit_id = $sku_detail[0]['unit_id'];

            $goods->bar_code = $sku_detail[0]['bar_code'];

            $goods->original_price = $sku_detail[0]['original_price'];

            $goods->crossed_price = $sku_detail[0]['crossed_price'];

            $goods->gross = $sku_detail[0]['gross'];

            $goods->quota = $quota;

            $goods->weight = $sku_detail[0]['weight'];

            $goods->category_id = implode(',',$category_id);

            $goods->sort = $sort;

            $goods->is_tui = $is_tui;

            $goods->is_open_yu = $is_open_yu;

            $goods->vip_discount_type = $vip_discount_type;

            if($is_open_yu == 1){

                $goods->yu_price = $yu_price;

                $goods->yu_days = $yu_days;

                $goods->yu_time_type = $yu_time_type;

            }

            $goods->cover_img = $cover_img;

            $goods->rotation = $rotation;

            $goods->goods_details = json_encode($goods_details);

            $goods->purchase_information = $purchase_information;

            $goods->other_sku_id = $other_sku_id?implode(',',$other_sku_id):$other_sku_id;

            $goods->show_type = $show_type?implode(',',$show_type):$show_type;

            $goods->online_sales = $online_sales;

            $goods->scan_code = $scan_code;

            $goods->support_business_type = $support_business_type?implode(',',$support_business_type):$support_business_type;

//            $goods->send_type = $send_type?implode(',',$send_type):$send_type;

            $goods->update_time = $this->request->time();

            $goods->status = $status;

            $goods->is_have_sku = count($sku_detail)>1?1:0;

            $goods->discount_detail = $vip_discount_type>0?json_encode($sku_detail[0]['discount_detail'],true):null;

            $goods->fictitious_take_count = $fictitious_take_count;

            $goods->start_sales_num = $sku_detail[0]['start_sales_num'];

            $goods->is_by_sales = $sku_detail[0]['is_by_sales'];

            $goods->buying_price = $sku_detail[0]['buying_price'];

            $goods->sku_info = $sku_detail[0]['sku_info'];

            $goods->products_info = $products_info?json_encode($products_info,true):null;

            $goods->save();

            //GoodsModel::where(['goods_id'=>$goods->goods_id,'shop_id'=>$this->request->shopId])->json(['discount_detail'],true)->update(['discount_detail'=>$discount_detail]);

            //规格操作
            if($goods->is_have_sku<1){
                GoodsSkuModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['goods_id','=',$goods->goods_id],

                    ['is_delete','=',0]

                ])->save(['is_delete'=>1]);
            }

            if($sku_detail && $goods->is_have_sku){

                $old_sku=GoodsSkuModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['goods_id','=',$goods->goods_id],

                    ['is_delete','=',0]

                ])->json(['discount_detail'],true)->select()->toArray();

                $update_goods_ids=array_column($sku_detail,'sku_id') ?? []; $delete_goods_sku=[];

                $old_sku_ids=array_column($old_sku,'sku_id') ?? [];

                foreach ($old_sku as $k => $v){

                    if(!in_array($v['sku_id'],$update_goods_ids)){

                        $v['is_delete']=1;

                        $delete_goods_sku[]=$v;

                    }

                }

                foreach ($sku_detail as $k => $v){

                    $sku_detail[$k]['shop_id']=$this->request->shopId;

                    $sku_detail[$k]['goods_id']=$goods->goods_id;

                    if(isset($v['sku_id'])){

                        if(!in_array($v['sku_id'],$old_sku_ids)) unset($sku_detail[$k]);

                    }
                    $sku_detail[$k]['discount_detail']= $vip_discount_type>0?json_encode($v['discount_detail'],true):null;

                }
                $new_sku=array_merge($sku_detail,$delete_goods_sku);
                //删除

                $goods_sku_model= new GoodsSkuModel();

                $goods_sku_model->saveAll($new_sku);


            }

            //分区打印
            if($goods_id && $old_depart_id!=$depart_id){
                ProduceModel::up(['is_delete'=>1],['goods_id'=>$goods->goods_id,'shop_id'=>$this->request->shopId,'depart_id'=>$old_depart_id,'is_delete'=>0]);
            }
            $produce = ProduceModel::where(['goods_id'=>$goods->goods_id,'shop_id'=>$this->request->shopId,'depart_id'=>$depart_id,'is_delete'=>0])->find();
            if(empty($produce)){
                $produce = new ProduceModel();
                $produce->depart_id = $depart_id;
                $produce->shop_id = $this->request->shopId;
                $produce->goods_id = $goods->goods_id;
                $produce->save();
            }
            //供应商
            if($supplier_id){
                $supplier = SupplierModel::info(['id'=>$supplier_id]);
                if(empty($supplier)) return $this->error('供应商不存在');
                $supplier_goods = SupplierGoodsModel::where(['shop_id'=>$this->request->shopId,'goods_id'=>$goods->goods_id,'is_delete'=>0])->find();
                if($supplier_goods){
                    SupplierGoodsModel::up(['supplier_id'=>$supplier_id],['id'=>$supplier_goods['id']]);
                }else{
                    $sg_data['shop_id'] = $this->request->shopId;
                    $sg_data['supplier_id'] = $supplier_id;
                    $sg_data['goods_id'] = $goods->goods_id;
                    SupplierGoodsModel::insertGetId($sg_data);
                }

            }
            /*扫码点餐第一版先不做
                        //门店开启扫码点餐并且产品选择了扫码点餐则同步到菜单管理（商品）(只有新增才同步)
                        if($goods_id<1 && $scan_code>0){

                            $scan_code_goods->type = 1;
                            $scan_code_goods->scan_code_goods_id = $goods->goods_id;
                            $scan_code_goods->save();

                            if($sku_detail && $goods->is_have_sku){

                                foreach ($sku_detail as $k => $v){
                                    $sku_detail[$k]['shop_id'] = $this->request->shopId;
                                    $sku_detail[$k]['goods_id'] = $scan_code_goods->goods_id;
                                    $sku_detail[$k]['discount_detail'] = json_encode($v['discount_detail'],true);

                                }
                                $goods_sku_model->saveAll($sku_detail);

                            }

                        }
                        */
            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        //图片操作
        imgReplaceAct($cover_img,$pre_cover_img);
        arrayNoUseImg($pre_rotation);
        arrayUseImg($rotation);
        arrayNoUseImg($pre_goods_details);
        arrayUseImg($goods_details);

        return $this->success('操作成功');

    }
    /**
     * 单独获取产品会员折扣
     */
    public function getDiscountDetail(){
        $goods_id = $this->request->param('goods_id/d',0);
        $goods = GoodsModel::where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId])
            ->json(['discount_detail'],true)
            ->find();

        if(null === $goods) {

            return $this->error($this->name.'不存在');

        }
        //会员折扣
        $discount_detail = $goods->discount_detail;
        if($goods->vip_discount_type>0 && $discount_detail){

            foreach ($discount_detail as $k=>$v){

                $level = LevelModel::find($v['level_id']);
                $discount_detail[$k]['name']=$level->name;
            }

        }

        if($goods->is_have_sku){

            $sku_list = GoodsSkuModel::where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId])
                    ->json(['discount_detail'],true)
                    ->select()->toArray() ?? [];

            foreach ($sku_list as $key=>$value){

                $sku_discount_detail = $value['discount_detail'];

                foreach ($sku_discount_detail as $k=>$v){

                    $level = LevelModel::find($v['level_id']);
                    $sku_list[$key]['discount_detail'][$k]['name']=$level?$level->name:'';
                }
                $sku_detail[] = [
                    'sku_id'=>$value['sku_id'],
                    'name'=>$value['name'],
                    'original_price'=>$value['original_price'],
                    'discount_detail'=>$sku_list[$key]['discount_detail']
                ];
            }

        }else{

            $sku_detail= [
                'sku_id'=>0,
                'name'=>$goods->sku_name,
                'original_price'=>$goods->original_price,
                'discount_detail'=>$discount_detail
            ];

        }
        $return_discount_detail = [
            'goods_id'=>$goods_id,
            'vip_discount_type'=>$goods->vip_discount_type,
            'name'=>$goods->name,
            'sku_detail'=>$sku_detail
        ];
        return $this->success(['detail'=>$return_discount_detail]);
    }
    /**
     * 单独修改会员折扣
     */
    public function saveVipDiscount()

    {

        $goods_id = $this->request->param('goods_id/d',0);
        $vip_discount_type = $this->request->param('vip_discount_type/d',0);
        $sku_detail = $this->request->param('sku_detail');
        $origin_type = $this->request->param('origin_type/d',1);

        $where[] = ['goods_id','=',$goods_id];
        $where[] = ['origin_type','=',$origin_type];
        $where[] = ['is_delete','=',0];
        $where[] = ['shop_id','=',$this->request->shopId];

        if(null === $goods= GoodsModel::where($where)->json(['discount_detail'],true)->find()) return $this->error($this->name.'不存在');

        //测试数据
//        $discount_detail[]=[
//            'level_id'=>7,
//            'member_price'=>8
//        ];
//
//        $discount_detail[]=[
//            'level_id'=>8,
//            'member_price'=>7
//        ];
//        $discount_detail[]=[
//            'level_id'=>9,
//            'member_price'=>6
//        ];
//        $discount_detail[]=[
//            'level_id'=>43,
//            'member_price'=>5
//        ];
//        $discount_detail[]=[
//            'level_id'=>47,
//            'member_price'=>4
//        ];
//
//        if($vip_discount_type>0){
//            $sku_detail[]=[
//                'sku_id'=>151,
//                'discount_detail'=>$discount_detail
//
//            ];
//        }

        if($sku_detail){
            //先修改goods表
            $goods->vip_discount_type = $vip_discount_type;
            if($vip_discount_type>0) $goods->discount_detail = json_encode($sku_detail[0]['discount_detail'],true);
            $goods->save();
            //在修改规格表
            if($vip_discount_type>0 && $goods->is_have_sku){
                $old_sku=GoodsSkuModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['goods_id','=',$goods->goods_id],

                    ['is_delete','=',0]

                ])->json(['discount_detail'],true)->select()->toArray();

                $old_sku_ids=array_column($old_sku,'sku_id') ?? [];

                foreach ($sku_detail as $k => $v){

                    if(isset($v['sku_id'])){

                        if(!in_array($v['sku_id'],$old_sku_ids)) unset($sku_detail[$k]);

                    }
                    $sku_detail[$k]['discount_detail']=json_encode($v['discount_detail'],true);

                }
                //删除

                $goods_sku_model= new GoodsSkuModel();

                $goods_sku_model->saveAll($sku_detail);
            }


        }

        return $this->success('操作成功');

    }
    /**
     *获取套餐
     */
    public function showSetMeal()

    {

        $goods_id = $this->request->param('goods_id/d',0);

        $goods = GoodsModel::with(['unit'=>function($query){
            $query->field('other_sku_detail_id,group_detail_name')
                ->where(['shop_id'=>$this->request->shopId,'is_delete'=>0]);
        }])->where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId,'type'=>3])->json(['discount_detail','use_limit_detail','goods_details'],true)->find();

        if(null === $goods) {

            return $this->error($this->set_meal_name.'不存在');

        }

        $goods->send_type = $goods->send_type?explode(',',$goods->send_type):$goods->send_type;
        $general_shop = $goods->general_shop?explode(',',$goods->general_shop):$goods->general_shop;
        if($general_shop){
            for($i=0;$i<count($general_shop);$i++){
                $general_shop[$i] = intval($general_shop[$i]);
            }
        }
        $goods->general_shop = $general_shop;
        $group = GoodsGroupModel::with(['groupDetail'])
                ->where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId])
                ->select()->toArray() ?? [];


        foreach ($group as $k=>$v){

            if($v['groupDetail']){
                foreach ($v['groupDetail'] as $key=>$value){
                    if($value['goods_id']){
                        $group_detail_goods = GoodsModel::with(['unit'])
                            ->where(['goods_id'=>$value['goods_id'],'is_delete'=>0,'shop_id'=>$this->request->shopId])
                            ->find();
                        $group[$k]['groupDetail'][$key]['name']= $group_detail_goods->name;
                        $group[$k]['groupDetail'][$key]['unit']= $group_detail_goods->unit->group_detail_name;
                        $group[$k]['groupDetail'][$key]['original_price']= $group_detail_goods->original_price;
                    }else{
                        $group[$k]['groupDetail'][$key]['name']= $value['goods_name'];
                        $group[$k]['groupDetail'][$key]['unit']= $value['unit_name'];
                        $group[$k]['groupDetail'][$key]['original_price']= $value['original_price'];
                    }

                }

            }

        }
        //秒杀
        $flash_sale = FlashSaleGoodsModel::where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId,'is_link_set_meal'=>1])->find();

        $goods->flash_sale = $flash_sale;
        $goods->group = $group;

        return $this->success(['detail'=>$goods]);

    }
    /**
     *新增/修改套餐
     */
    public function saveSetMeal()

    {

        $goods_id = $this->request->param('goods_id/d',0);

        $sort = $this->request->param('sort');

        $name = $this->request->param('name');

        $bar_code=$this->request->param('bar_code');

        $unit_id=$this->request->param('unit_id/d',0);

        $total_value=$this->request->param('total_value/f',0);

        $original_price=$this->request->param('original_price/f',0);

        $gross=$this->request->param('gross/f',0);

        $quota=$this->request->param('quota/d',0);

        $weight=$this->request->param('weight/f',0);

        $vip_discount_type = $this->request->param('vip_discount_type/d',0);

        $cover_img = $this->request->param('cover_img');

        $rotation = $this->request->param('rotation/a',[]);

        $goods_details = $this->request->param('goods_details/a',[]);

        $purchase_information = $this->request->param('purchase_information');

        $is_open_yu = $this->request->param('is_open_yu/d',0);

        $yu_price = $this->request->param('yu_price/f',0);

        $yu_time_type = $this->request->param('yu_time_type/d',1);

        $yu_days = $this->request->param('yu_days/d',0);

        $type = $this->request->param('type/d',3);

        $use_type = $this->request->param('use_type/d',1);

        $use_time_type = $this->request->param('use_time_type/d',1);

        $use_time_num = $this->request->param('use_time_num/d',1);

        $use_start_time = $this->request->param('use_start_time');

        $use_end_time = $this->request->param('use_end_time');

        $use_limit = $this->request->param('use_limit/d',1);

        $is_limit_buy = $this->request->param('is_limit_buy/d',0);

        $can_buy_type = $this->request->param('can_buy_type/d',1);

        $can_buy_num = $this->request->param('can_buy_num/d',0);

        $is_need_appointment = $this->request->param('is_need_appointment/d',0);

        $appointment_explain = $this->request->param('appointment_explain');

        $sell_time_type = $this->request->param('sell_time_type/d',0);

        $sell_start_time = $this->request->param('sell_start_time');

        $sell_end_time = $this->request->param('sell_end_time');

        $remarks = $this->request->param('remarks');

        $is_limit_time_flash = $this->request->param('is_limit_time_flash/d',0);

//        $flash_sale_goods_id = $this->request->param('flash_sale_goods_id/d',0);//关联的秒杀id

        $is_tui = $this->request->param('is_tui/d',0);

        $online_sales = $this->request->param('online_sales/d',-1);

        $general_shop = $this->request->param('general_shop');

        $send_type = $this->request->param('send_type');

        $status = $this->request->param('status/d',-1);

        $discount_detail = $this->request->param('discount_detail');

        $sku_detail = $this->request->param('sku/a',[]);

        $group_data = $this->request->param('group/a',[]);

        $use_limit_detail = $this->request->param('use_limit_detail');

        $fictitious_take_count = $this->request->param('fictitious_take_count/d',0);

        $flash_sales = $this->request->param('flash_sale/a',[]);

        $flash_sale = $flash_sales?$flash_sales[0]:$flash_sales;
        //测试数据
        /*
        $discount_detail[]=[
            'level_id'=>7,
            'member_price'=>9
        ];

        $discount_detail[]=[
            'level_id'=>8,
            'member_price'=>8
        ];
        $discount_detail[]=[
            'level_id'=>9,
            'member_price'=>7
        ];
        $discount_detail[]=[
            'level_id'=>43,
            'member_price'=>6
        ];
        $discount_detail[]=[
            'level_id'=>47,
            'member_price'=>5
        ];


        $group_detail[]=[
            'goods_id'=>182,
            'sku_id'=>0,
            'num'=>1,
            'is_once_complete'=>0,
            'once_limit_num'=>1,
            'end_type'=>1,
            'end_time_num'=>10,
            'end_time_type'=>2,
            'sort'=>0,
        ];
        $group_data[]=[
            'group_name'=>'大套餐分组',
            'type'=>4,
            'num'=>3,
            'choose_num'=>0,
            'is_choose_same'=>0,
            'group_detail'=>$group_detail

        ];

        $use_limit_detail[]=[
            'week'=>[1,2],
            'start_time'=>'08:00',
            'end_time'=>'22:00'
        ];

        $flash_sale['flash_sale_price']=10;
        $flash_sale['gross']=1;
        $flash_sale['start_time']='2023-4-8 00:00:00';
        $flash_sale['end_time']='2023-5-8 00:00:00';;
        $flash_sale['is_limit_buy']=0;
        $flash_sale['limit_buy_type']=0;
        $flash_sale['limit_buy_num']=0;
        $flash_sale['is_limit_num']=0;
        $flash_sale['limit_num_type']=2;
        $flash_sale['quota']=100;
        $flash_sale['is_tui']=0;
        $flash_sale['flash_sale_info']='1';
        */

        //判断传来的参数

//        if(empty($name)) return $this->error('请输入名称');

        if(!in_array($is_tui,[0,1])) return $this->error('未设置是否推荐');

        if(!in_array($is_open_yu,[0,1])) return $this->error('未设置是否开启预售');

        if(!in_array($vip_discount_type,[0,1,2,3])) return $this->error('未设置会员价类型');

        if($is_open_yu==1){

            if(empty($yu_price) || $yu_price<=0) return $this->error('请输入预售价格，且不能小于0');

            if(empty($yu_days) || $yu_days <= 0) return $this->error('请输入预售支付后几天发货');

        }
        if(!$discount_detail && $vip_discount_type>0) return $this->error('会员折扣不能为空');

        if(empty($cover_img)) return $this->error('请上传缩略图');

        if(empty($rotation)) $rotation[] = $cover_img;

        if(empty($rotation) || !is_array($rotation) || count($rotation)>5) return $this->error('请上传轮播图，且数量不能多余5个');

//        if(empty($goods_details)) return $this->error('请填写商品详情');

//        if(empty($purchase_information)) return $this->error('请输入购买须知');

        if($is_limit_time_flash && empty($flash_sale)) return $this->error('请设置秒杀信息');

        if(count($group_data)<1) return $this->error('至少一个分组');

//        if($flash_sale_goods_id){
//
//            $set_meal_flash_sale = FlashSaleGoodsModel::where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId,'is_link_set_meal'=>1])->find();
//
//            if(!$set_meal_flash_sale || $set_meal_flash_sale->flash_sale_goods_id!=$flash_sale_goods_id){
//
//                return $this->error('秒杀数据有误');
//            }
//        }


        //保存操作
        if($goods_id != 0){

            if(null === $goods= GoodsModel::find($goods_id)) return $this->error($this->name.'不存在');

            //之前的商品不能修改
            if($goods->add_time){

            }
            if($goods->is_delete!=0) return $this->error($this->name.'不存在');

            if($goods->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

            $pre_cover_img=$goods->cover_img; $pre_rotation=$goods->rotation; $pre_goods_details=$goods_details;

        }else{

            $goods = new GoodsModel();

            $goods->shop_id = $this->request->shopId;

            $pre_cover_img=null; $pre_rotation=[]; $pre_goods_details=[];

        }

        Db::startTrans();

        try{
            //默认添加套餐分类（商家不能修改和删除）
            if(null === $category = GoodsCategoryModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'name'=>'套餐','is_no_update'=>1,'type'=>2])->find()){
                $category = new GoodsCategoryModel();
                $category->shop_id = $this->request->shopId;
                $category->name = '套餐';
                $category->pid = 0;
                $category->sort = 0;
                $category->type = 2;
                $category->is_no_update = 1;
                $category->save();
            }

            $goods->category_id = $category->category_id;

            $goods->name = $name;

            $goods->sort=$sort;

//            $goods->bar_code = $bar_code;

            $goods->unit_id = $unit_id;

            $goods->total_value = $total_value;

            $goods->original_price = $original_price;

            $goods->gross = $gross;

            $goods->quota = $quota;

//            $goods->weight = $weight;

            $goods->is_tui=$is_tui;

            $goods->is_open_yu=$is_open_yu;

            $goods->vip_discount_type=$vip_discount_type;

            if($is_open_yu==1){

                $goods->yu_price=$yu_price;

                $goods->yu_days=$yu_days;

                $goods->yu_time_type=$yu_time_type;

            }

            $goods->cover_img=$cover_img;

            $goods->rotation=$rotation;

            $goods->goods_details=$goods_details?json_encode($goods_details):$goods_details;

            $goods->purchase_information=$purchase_information;

            $goods->online_sales=$online_sales;

//            $goods->send_type=$send_type?implode(',',$send_type):$send_type;

            $goods->update_time=$this->request->time();

            $goods->status=$status;

            $goods->type=$type;

            $goods->use_type=$use_type;

            $goods->use_time_type=$use_time_type;

            $goods->use_time_num=$use_time_num;

            if($use_type==3) $goods->use_start_time=$use_start_time;

            if($use_type==3) $goods->use_end_time=$use_end_time;

            $goods->use_limit=$use_limit;

            $goods->use_limit_detail=$use_limit_detail?json_encode($use_limit_detail,true):$use_limit_detail;

            $goods->is_limit_buy=$is_limit_buy;

            $goods->can_buy_type=$can_buy_type;

            $goods->can_buy_num=$can_buy_num;

            $goods->is_need_appointment=$is_need_appointment;

            $goods->appointment_explain=$appointment_explain;

            $goods->sell_time_type=$sell_time_type;

            $goods->sell_start_time=$sell_start_time;

            $goods->sell_end_time=$sell_end_time;

            $goods->remarks=$remarks;

            $goods->is_limit_time_flash=$is_limit_time_flash;

            $goods->general_shop=$general_shop?implode(',',$general_shop):$general_shop;

            $goods->discount_detail=json_encode($discount_detail,true);

            $goods->fictitious_take_count = $fictitious_take_count;

            $goods->save();


            //GoodsModel::where(['goods_id'=>$goods->goods_id,'shop_id'=>$this->request->shopId])->json(['discount_detail'],true)->update(['discount_detail'=>$discount_detail]);

            //规格操作


            //套餐明细
            if($group_data){

                $goods_group_model= new GoodsGroupModel();
                $goods_group_detail_model= new GoodsGroupDetailModel();

                if($goods_id){
                    //分组和分组明细一起删
                    $goods_group_model->where(['shop_id'=>$this->request->shopId,'goods_id'=>$goods_id])->update(['is_delete'=>1]);
                    $goods_group_detail_model->where(['shop_id'=>$this->request->shopId,'goods_id'=>$goods_id])->update(['is_delete'=>1]);
                }

                foreach ($group_data as $key=>$value){
                    $group=[
                        'shop_id'=>$this->request->shopId,
                        'goods_id'=>$goods->goods_id,
                        'group_name'=>$value['group_name'],
                        'type'=>$value['type'],
                        'num'=>$value['num'],
                        'choose_num'=>$value['choose_num'],
                        'is_choose_same'=>$value['is_choose_same'],
                    ];

                    $goods_group_id = $goods_group_model->insertGetId($group);

                    if($value['groupDetail']){
                        $goods_group_detail=[];
                        foreach ($value['groupDetail'] as $k=>$v){
                            //是否直接填并未选取产品
                            if($v['goods_id']){
                                $goods_group_detail[] = [
                                    'shop_id'=>$this->request->shopId,
                                    'goods_group_id'=>$goods_group_id,
                                    'goods_id'=>$v['goods_id'],
                                    'sku_id'=>$v['sku_id'],
                                    'num'=>$v['num'],
                                    'use_condition'=>$v['use_condition'],
                                    'once_limit_num'=>$v['once_limit_num'],
                                    'end_type'=>$v['end_type'],
                                    'end_time_num'=>$v['end_time_num'],
                                    'end_time_type'=>$v['end_time_type'],
                                    'sort'=>$v['sort'],
                                    'unit_id'=>$v['unit_id']
                                ];
                            }else{
                                $unit = GoodsOtherSkuDetailModel::where(['type'=>3,'is_delete'=>0,'other_sku_detail_id'=>$v['unit_id']])->find();
                                $goods_group_detail[] = [
                                    'shop_id'=>$this->request->shopId,
                                    'goods_name'=>$v['name'],
                                    'unit_name'=>$unit->group_detail_name,
                                    'original_price'=>$v['original_price'],
                                    'goods_group_id'=>$goods_group_id,
                                    'goods_id'=>$v['goods_id'],
                                    'num'=>$v['num'],
                                    'use_condition'=>$v['use_condition'],
                                    'once_limit_num'=>$v['once_limit_num'],
                                    'end_type'=>$v['end_type'],
                                    'end_time_num'=>$v['end_time_num'],
                                    'end_time_type'=>$v['end_time_type'],
                                    'sort'=>$v['sort'],
                                    'unit_id'=>$v['unit_id']
                                ];
                            }

                        }

                        $goods_group_detail_model->saveAll($goods_group_detail);
                    }

                }

            }
            //限时秒杀
            if($is_limit_time_flash && $goods_id<1){

                //if(null === $flash_sale_goods= FlashSaleGoodsModel::where(['flash_sale_goods_id'=>$flash_sale_goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId,'is_link_set_meal'=>1])->find()){}
                $flash_sale_goods = new FlashSaleGoodsModel();
                $flash_sale_goods->shop_id = $this->request->shopId;
                $flash_sale_goods->goods_id = $goods->goods_id;
                $flash_sale_goods->is_link_set_meal = 1;
                $flash_sale_goods->flash_sale_price = $flash_sale['flash_sale_price'];
                $flash_sale_goods->gross = $flash_sale['gross'];
                $flash_sale_goods->start_time = $flash_sale['start_time'];
                $flash_sale_goods->end_time = $flash_sale['end_time'];
                $flash_sale_goods->is_limit_buy = $flash_sale['is_limit_buy'];
                $flash_sale_goods->limit_buy_type = $flash_sale['limit_buy_type'];
                $flash_sale_goods->limit_buy_num = $flash_sale['limit_buy_num'];
                $flash_sale_goods->is_limit_num = $flash_sale['is_limit_num'];
                $flash_sale_goods->limit_num_type = $flash_sale['limit_num_type'];
                $flash_sale_goods->quota = $flash_sale['limit_num_type']==1?$flash_sale['quota']:$quota;
                $flash_sale_goods->is_tui = $flash_sale['is_tui'];
                $flash_sale_goods->flash_sale_info = $flash_sale['flash_sale_info'];
                $flash_sale_goods->save();
            }

            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

        //图片操作
        imgReplaceAct($cover_img,$pre_cover_img);
        arrayNoUseImg($pre_rotation);
        arrayUseImg($rotation);
        arrayNoUseImg($pre_goods_details);
        arrayUseImg($goods_details);

        return $this->success('操作成功');

    }

    //查询产品分类
    protected function getCategoryTreeData($pid=0)

    {

        $return=[];

        $category= GoodsCategoryModel::where([

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['pid','=',$pid],

            ['type','=',1]

        ])->select()->toArray();

        if(!empty($category)){

            foreach ($category as $k => $v){

                $return[$k]=[

                    'title'=>$v['name'],

                    'value'=>$v['category_id'],

                    'key'=>$v['category_id'],

                    'children'=> $this->getCategoryTreeData($v['category_id']),

                ];

            }

        }

        return $return;

    }
    /**
     *上架/下架
     */
    public function saveStatus()

    {

        $goods_id = $this->request->param('goods_id/d',0);
        $status = $this->request->param('status');

        if(!in_array($status,[1,-1]))  return $this->error('状态有误');

        if(null === $goods= GoodsModel::find($goods_id)) return $this->error('不存在');
        if($goods->is_delete!=0) return $this->error('不存在');
        if($goods->shop_id != $this->request->shopId) return $this->error('不存在');

        //其他判断后面补充
        if($goods->type == 2){
            //判断有没有套餐关联了该产品
            $goods_arr = GoodsGroupDetailModel::where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId])->select()->toArray()??[];
            if($goods_arr){
                return $this->error('该产品已被套餐关联，需要删除关联的产品，才能下架');
            }
            //判断有没有会员折扣关联该产品
//            $level_benefits = LevelBenefitsModel::where(['goods_id'=>$goods_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
//            if($level_benefits){
//                return $this->error('该产品已被会员折扣关联，需要删除关联的产品，才能下架');
//            }
        }


        $goods->status = $status;
        $goods->save();

        return $this->success('操作成功');

    }
    /**
     *删除（产品或套餐、菜单）
     */
    public function del()

    {

        $goods_id = $this->request->param('goods_id');

        //其他判断后面补充

        //判断有没有套餐关联了该产品
        $goods = GoodsGroupDetailModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->whereIn('goods_id',$goods_id)->select()->toArray()??[];

        if($goods){
            return $this->error('该产品已被套餐关联，需要删除关联的产品，才能下架');
        }
        //判断有没有会员折扣关联该产品
//        $level_benefits = LevelBenefitsModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->whereIn('goods_id',$goods_id)->find();
//        if($level_benefits){
//            return $this->error('该产品已被会员折扣关联，需要删除关联的产品，才能下架');
//        }
        $goods_group_ids = GoodsGroupModel::where(['shop_id'=>$this->request->shopId])->whereIn('goods_id',$goods_id)->column('goods_group_id');
        GoodsModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->whereIn('goods_id',$goods_id)->update(['is_delete'=>1]);
        GoodsGroupModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->whereIn('goods_id',$goods_id)->update(['is_delete'=>1]);
        GoodsGroupDetailModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0])->whereIn('goods_group_id',$goods_group_ids)->update(['is_delete'=>1]);

        return $this->success('操作成功');

    }
    /**
     * 删除产品或套餐的分类
     */
    public function delCategoty(){
        $goods_id = $this->request->param('goods_id');
        $category_id = $this->request->param('category_id');

        $goods = GoodsModel::where(['goods_id'=>$goods_id,'is_delete'=>0,'shop_id'=>$this->request->shopId])->find();
        if(null === $goods) return $this->error($this->name.'不存在');

        $category_ids_arr = explode(',',$goods->category_id);
        $key = array_search($category_id,$category_ids_arr,true);
        if($key!==false){
            unset($category_ids_arr[$key]);
        }
        if(count($category_ids_arr)<1){
            return $this->error($this->name.'至少一个分类');
        }
        $goods->category_id = implode(',',$category_ids_arr);
        $goods->save();
        return $this->success('操作成功');
    }
    /**
     * 产品库导入菜单
     */
    public function importMenu(){
        $goods_ids = $this->request->param('goods_id/a',[]);//产品
        $set_meal_goods_ids = $this->request->param('set_meal_goods_id/a',[]);//套餐

        Db::startTrans();

        try{
            //产品导入
            $this->goodsImportMenu($goods_ids);
            //套餐导入
            $this->setMealImportMenu($set_meal_goods_ids);

            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

        return $this->success('操作成功');

    }
    /**
     * 产品导入
     */
    private function goodsImportMenu($goods_ids){
        $goods_model = new GoodsModel();
        $goods_sku_model = new GoodsSkuModel();

        foreach ($goods_ids as $k=>$v){
            //产品
            if(null === $goods = $goods_model->where(['goods_id'=>$v,'is_delete'=>0,'shop_id'=>$this->request->shopId,'type'=>2])->find()){
                return $this->error('id为'.$v.'不存在');
            }
            $menu_goods = $goods->toArray();
            $menu_goods['type'] = 1;
            $menu_goods['add_time'] = request()->time();
            $menu_goods['add_ip'] = request()->ip();
            $menu_goods['take_count'] = 0;
            unset($menu_goods['goods_id']);

            $goods_id = $goods_model->insertGetId($menu_goods);
            //规格
            if($goods_sku = $goods_sku_model->where(['goods_id'=>$v,'is_delete'=>0,'shop_id'=>$this->request->shopId])->select()->toArray()){

                foreach ($goods_sku as $key=>$value){
                    $menu_goods_sku[$key] = $value;
                    $menu_goods_sku[$key]['goods_id'] = $goods_id;
                    $menu_goods_sku[$key]['add_time'] = request()->time();
                    $menu_goods_sku[$key]['add_ip'] = request()->ip();
                    $menu_goods_sku[$key]['take_count'] = 0;
                    unset($menu_goods_sku[$key]['sku_id']);
                }

                $goods_sku_model->saveAll($menu_goods_sku);

            }
        }
    }
    /**
     * 套餐导入
     */
    private function setMealImportMenu($set_meal_goods_ids){
        $goods_model = new GoodsModel();
        $goods_group_model = new GoodsGroupModel();
        $goods_group_detail_model = new GoodsGroupDetailModel();

        foreach ($set_meal_goods_ids as $k=>$v){
            //套餐
            if(null === $goods = $goods_model->where(['goods_id'=>$v,'is_delete'=>0,'shop_id'=>$this->request->shopId,'type'=>3])->find()){
                return $this->error('id为'.$v.'不存在');
            }
            $menu_goods = $goods->toArray();
            $menu_goods['type'] = 1;
            $menu_goods['add_time'] = request()->time();
            $menu_goods['add_ip'] = request()->ip();
            $menu_goods['take_count'] = 0;
            unset($menu_goods['goods_id']);

            $goods_id = $goods_model->insertGetId($menu_goods);
            //分组
            if($goods_group = $goods_group_model->where(['goods_id'=>$v,'is_delete'=>0,'shop_id'=>$this->request->shopId])->select()->toArray()){
                foreach ($goods_group as $key=>$value){
                    $menu_goods_group = $value;
                    $menu_goods_group['goods_id'] = $goods_id;
                    unset($menu_goods_group['goods_group_id']);

                    $goods_group_id = $goods_group_model->insertGetId($menu_goods_group);
                    //分组详情
                    if($goods_group_detail = $goods_group_detail_model->where(['goods_id'=>$v,'goods_group_id'=>$value['goods_group_id'],'is_delete'=>0,'shop_id'=>$this->request->shopId])->select()->toArray()){
                        foreach ($goods_group_detail as $kk=>$vv){
                            $menu_goods_group_detail[$kk] = $vv;
                            $menu_goods_group_detail[$kk]['goods_id'] = $goods_id;
                            $menu_goods_group_detail[$kk]['goods_group_id'] = $goods_group_id;
                            unset($menu_goods_group_detail[$kk]['goods_group_detail_id']);
                        }
                        $goods_group_detail_model->saveAll($menu_goods_group_detail);
                    }
                }
            }
        }
    }

    /**
     * 通用门店
     */
    public function generalShop(){
        $shop_account = ShopAccountModel::where(['shop_id'=>$this->request->shopId])->find();
        $shop = [];
        if($shop_account->account_id){
            $shop_ids = ShopAccountModel::where(['account_id'=>$shop_account->account_id])->where('shop_id','not in',[35,$this->request->shopId])->column('shop_id');
            $shop = ShopModel::whereIn('shop_id',$shop_ids)->field('shop_id,name')->select();
        }
        $return = [
            'count'=>count($shop),
            'shop'=>$shop
        ];
        return $this->success($return);
    }

}

